
#include <fstream>
#include <iostream>
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "protobuf/text_format.h"
#include "gps.pb.h"
#include "gpx_parser.h"
#include "date_time.h"

DEFINE_string(ingpb, "", "file.gpb");
DEFINE_string(outcsv, "", "file.csv");

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, false);
  if (FLAGS_ingpb.empty()) {
    LOG(ERROR) << "missing arg --ingpb file.gpb";
    return 1;
  }
  if (FLAGS_outcsv.empty()) {
    LOG(ERROR) << "missing arg --outcsv file.csv";
    return 1;
  }
  std::ifstream input_gpb(FLAGS_ingpb.c_str(),
                          std::ios_base::in|std::ios_base::binary);
  std::ofstream output_csv(FLAGS_outcsv.c_str(),
                           std::ios_base::out|std::ios_base::binary);
  gps_proto::GpsProto gps_proto;
  gps_proto.ParseFromIstream(&input_gpb);

  for (int t = 0; t < gps_proto.track_size(); ++t) {
    const gps_proto::TrackProto& track_proto = gps_proto.track(t);
    for (int s = 0; s < track_proto.segment_size(); ++s) {
      const gps_proto::SegmentProto& segment_proto = track_proto.segment(s);
      int point_size = segment_proto.point_size();
      if (point_size == 0) {
        continue;
      }
      for (int p = 0; p < point_size; ++p) {
        const gps_proto::PointProto& point_proto = segment_proto.point(p);
        output_csv << "trk" << t << ","
                   << "seg" << s << ","
                   << point_proto.lat() << " " << point_proto.lon() << ","
                   << point_proto.ele() << ","
                   << point_proto.time() << std::endl;
            
      }
    }
  }
  output_csv.flush();
}
